package com.cdream.basic.algorithm.leetcode.sort;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author cdream
 * @date 7/6/21
 */
public class Question1418 {
    public List<List<String>> displayTable(List<List<String>> orders) {
        List<List<String>> res = new ArrayList<>();
        // 1. 造表头
        List<String> header = orders.stream().map(a->a.get(2)).distinct().sorted().collect(Collectors.toList());
        header.add(0,"Table");
        res.add(header);
        // 2. 表头弄成hash表
        Map<String,Integer> cookieIndexMap = new HashMap<String,Integer>();
        for(int i = 0; i<header.size();i++){
            cookieIndexMap.put(header.get(i),i);
        }
        // 3. 制造行
        Map<Integer,List<Integer>> rowMap = new HashMap<>();
        for(List<String> order :orders){
            Integer[] a = new Integer[header.size()];
            Arrays.fill(a,0);
            List<Integer> ts = Arrays.asList(a);
            int table = Integer.parseInt(order.get(1));
            List<Integer> row = rowMap.getOrDefault(table,
                    new ArrayList<>(ts));
            row.set(0,table);
            int cookieIndex = cookieIndexMap.get(order.get(2));
            row.set(cookieIndex,row.get(cookieIndex)+1);
            rowMap.put(table,row);
        }
        List<List<String>> rows = rowMap.values().stream()
                .sorted(Comparator.comparingInt(a -> a.get(0)))
                .map(a->a.stream().map(String::valueOf).collect(Collectors.toList()))
                .collect(Collectors.toList());
        res.addAll(rows);
        return res;
    }

    public static void main(String[] args) {
        List<List<String>> param = new ArrayList<>();
        List<String> one = new ArrayList<>();
        one.add("David");
        one.add("3");
        one.add("Ceviche");
        param.add(one);
        System.out.println(new Question1418().displayTable(param));
    }
}
